package com.kgcx.common.handler;

import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.utils.CollectionUtils;
import com.kgcx.common.utils.ReflectHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Field;

/**
 * 拦截所有返回的json对象，如发现xss，转译
 *
 * @author 吴刚林
 * @date 2017/11/26
 */
@ControllerAdvice
@Slf4j
public class XssResponseBodyAdviceAdapter implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Nullable
    @Override
    public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (null != body && body instanceof ReturnData) {
            ReturnData returnData = (ReturnData) body;
            if (null != returnData.getData()) {
                CollectionUtils.runOnObjectOrCollection(returnData.getData(), d -> {
                    Field[] declaredFields = d.getClass().getDeclaredFields();
                    if (ArrayUtils.isNotEmpty(declaredFields)) {
                        for (Field declaredField : declaredFields) {
                            if (declaredField.getType().equals(String.class)) {
                                Object fieldValueObj = ReflectHelper.getFieldValue(d, declaredField.getName());
                                if (null != fieldValueObj) {
                                    String value = fieldValueObj.toString();
                                    if (StringUtils.containsAny(value, "&lt;", "&gt;", "&#40;", "&#41;", "&#39;")) {
                                        value = value.replaceAll("&lt;", "<").replaceAll("&gt;", ">");

                                        value = value.replaceAll("&#40;", "\\(").replaceAll("&#41;", "\\)");

                                        value = value.replaceAll("&#39;", "'");

                                        ReflectHelper.setFieldValue(d, declaredField.getName(), value);
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }
        return body;
    }
}
